class OCRScanner {
    constructor() {
        this.worker = null;
        this.currentImage = null;
        this.startTime = null;
        this.isProcessing = false;
        
        this.initializeElements();
        this.bindEvents();
        this.setupDragAndDrop();
    }

    initializeElements() {
        // 获取DOM元素
        this.uploadArea = document.getElementById('uploadArea');
        this.fileInput = document.getElementById('fileInput');
        this.uploadBtn = document.getElementById('uploadBtn');
        this.languageSelect = document.getElementById('language');
        this.processingSection = document.getElementById('processingSection');
        this.previewImage = document.getElementById('previewImage');
        this.imageInfo = document.getElementById('imageInfo');
        this.scanBtn = document.getElementById('scanBtn');
        this.resetBtn = document.getElementById('resetBtn');
        this.progressContainer = document.getElementById('progressContainer');
        this.progressFill = document.getElementById('progressFill');
        this.progressText = document.getElementById('progressText');
        this.resultSection = document.getElementById('resultSection');
        this.resultText = document.getElementById('resultText');
        this.confidence = document.getElementById('confidence');
        this.copyBtn = document.getElementById('copyBtn');
        this.downloadBtn = document.getElementById('downloadBtn');
        this.toggleDetails = document.getElementById('toggleDetails');
        this.detailsContent = document.getElementById('detailsContent');
        this.paragraphCount = document.getElementById('paragraphCount');
        this.lineCount = document.getElementById('lineCount');
        this.wordCount = document.getElementById('wordCount');
        this.processingTime = document.getElementById('processingTime');
        this.toast = document.getElementById('toast');
        this.loadingOverlay = document.getElementById('loadingOverlay');
    }

    bindEvents() {
        // 绑定事件监听器
        this.uploadBtn.addEventListener('click', (e) => {
            e.stopPropagation(); // 阻止事件冒泡
            this.fileInput.click();
        });
        this.fileInput.addEventListener('change', (e) => this.handleFileSelect(e));
        this.uploadArea.addEventListener('click', (e) => {
            // 只有当点击的不是按钮本身时才触发文件选择
            if (e.target !== this.uploadBtn && !this.uploadBtn.contains(e.target)) {
                this.fileInput.click();
            }
        });
        this.scanBtn.addEventListener('click', () => this.startOCR());
        this.resetBtn.addEventListener('click', () => this.reset());
        this.copyBtn.addEventListener('click', () => this.copyToClipboard());
        this.downloadBtn.addEventListener('click', () => this.downloadText());
        this.toggleDetails.addEventListener('click', () => this.toggleDetailsView());
        
        // 阻止默认的拖拽行为
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            this.uploadArea.addEventListener(eventName, this.preventDefaults, false);
            document.body.addEventListener(eventName, this.preventDefaults, false);
        });
    }

    setupDragAndDrop() {
        // 设置拖拽功能
        this.uploadArea.addEventListener('dragenter', () => this.highlight());
        this.uploadArea.addEventListener('dragover', () => this.highlight());
        this.uploadArea.addEventListener('dragleave', () => this.unhighlight());
        this.uploadArea.addEventListener('drop', (e) => this.handleDrop(e));
    }

    preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
    }

    highlight() {
        this.uploadArea.classList.add('dragover');
    }

    unhighlight() {
        this.uploadArea.classList.remove('dragover');
    }

    handleDrop(e) {
        this.unhighlight();
        const files = e.dataTransfer.files;
        if (files.length > 0) {
            this.handleFile(files[0]);
        }
    }

    handleFileSelect(e) {
        const file = e.target.files[0];
        if (file) {
            this.handleFile(file);
        }
    }

    handleFile(file) {
        // 检查文件类型
        if (!file.type.startsWith('image/')) {
            this.showToast('请选择有效的图片文件', 'error');
            return;
        }

        // 检查文件大小 (10MB限制)
        if (file.size > 10 * 1024 * 1024) {
            this.showToast('图片文件不能超过10MB', 'error');
            return;
        }

        this.currentImage = file;
        this.previewImage.src = URL.createObjectURL(file);
        this.showImageInfo(file);
        this.processingSection.style.display = 'block';
        this.resultSection.style.display = 'none';
        this.scanBtn.disabled = false;
    }

    showImageInfo(file) {
        const img = new Image();
        img.onload = () => {
            const info = `
                文件名: ${file.name}<br>
                文件大小: ${this.formatFileSize(file.size)}<br>
                图片尺寸: ${img.width} × ${img.height}px<br>
                文件类型: ${file.type}
            `;
            this.imageInfo.innerHTML = info;
        };
        img.src = URL.createObjectURL(file);
    }

    formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    async startOCR() {
        if (this.isProcessing || !this.currentImage) return;
        
        this.isProcessing = true;
        this.startTime = Date.now();
        this.scanBtn.disabled = true;
        this.resetBtn.disabled = true;
        this.progressContainer.style.display = 'block';
        this.resultSection.style.display = 'none';
        
        try {
            // 显示加载遮罩
            this.loadingOverlay.style.display = 'flex';
            
            // 获取选择的语言
            const language = this.languageSelect.value;
            
            // 创建Tesseract worker
            this.updateProgress(0, '正在初始化 OCR 引擎...');
            
            // 使用Tesseract.js进行OCR识别
            const result = await Tesseract.recognize(this.currentImage, language, {
                logger: (m) => {
                    if (m.status === 'recognizing text') {
                        const progress = Math.round(m.progress * 100);
                        this.updateProgress(progress, `正在识别文字... ${progress}%`);
                    }
                }
            });

            // 隐藏加载遮罩
            this.loadingOverlay.style.display = 'none';
            
            // 处理识别结果
            this.handleOCRResult(result);
            
        } catch (error) {
            console.error('OCR识别失败:', error);
            this.loadingOverlay.style.display = 'none';
            this.showToast('OCR识别失败，请重试', 'error');
        } finally {
            this.isProcessing = false;
            this.scanBtn.disabled = false;
            this.resetBtn.disabled = false;
            this.progressContainer.style.display = 'none';
        }
    }

    updateProgress(percentage, text) {
        this.progressFill.style.width = `${percentage}%`;
        this.progressText.textContent = text;
    }

    handleOCRResult(result) {
        const endTime = Date.now();
        const processingTimeMs = endTime - this.startTime;
        
        // 显示识别结果
        this.resultText.value = result.data.text;
        
        console.log("识别信息",result.data);
        // 设置置信度
        const confidenceValue = Math.round(result.data.confidence);
        this.confidence.textContent = `${confidenceValue}%`;
        this.confidence.className = 'confidence-value';
        
        if (confidenceValue >= 80) {
            this.confidence.classList.add('high');
        } else if (confidenceValue >= 60) {
            this.confidence.classList.add('medium');
        } else {
            this.confidence.classList.add('low');
        }
        
        // 统计信息
        this.updateStatistics(result.data, processingTimeMs);
        
        // 显示结果区域
        this.resultSection.style.display = 'block';
        
        // 滚动到结果区域
        this.resultSection.scrollIntoView({ behavior: 'smooth' });
        
        this.showToast('文字识别完成！', 'success');
    }

    updateStatistics(data, processingTime) {
        // 计算统计信息
        const paragraphs = data.paragraphs ? data.paragraphs.length : 0;
        const lines = data.lines ? data.lines.length : 0;
        const words = data.words ? data.words.length : 0;
        
        this.paragraphCount.textContent = paragraphs;
        this.lineCount.textContent = lines;
        this.wordCount.textContent = words;
        this.processingTime.textContent = `${(processingTime / 1000).toFixed(1)}秒`;
    }

    async copyToClipboard() {
        try {
            await navigator.clipboard.writeText(this.resultText.value);
            this.showToast('文本已复制到剪贴板', 'success');
        } catch (error) {
            // 降级方案
            this.resultText.select();
            document.execCommand('copy');
            this.showToast('文本已复制到剪贴板', 'success');
        }
    }

    downloadText() {
        const text = this.resultText.value;
        if (!text.trim()) {
            this.showToast('没有可下载的文本内容', 'warning');
            return;
        }

        const blob = new Blob([text], { type: 'text/plain;charset=utf-8' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `OCR_结果_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.txt`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
        
        this.showToast('文本文件已下载', 'success');
    }

    toggleDetailsView() {
        const isVisible = this.detailsContent.style.display !== 'none';
        this.detailsContent.style.display = isVisible ? 'none' : 'block';
        this.toggleDetails.textContent = isVisible ? '查看详细信息' : '隐藏详细信息';
    }

    reset() {
        // 重置所有状态
        this.currentImage = null;
        this.fileInput.value = '';
        this.processingSection.style.display = 'none';
        this.resultSection.style.display = 'none';
        this.progressContainer.style.display = 'none';
        this.detailsContent.style.display = 'none';
        this.toggleDetails.textContent = '查看详细信息';
        this.scanBtn.disabled = true;
        this.isProcessing = false;
        
        // 清理对象URL
        if (this.previewImage.src.startsWith('blob:')) {
            URL.revokeObjectURL(this.previewImage.src);
        }
        
        this.showToast('已重置，可以选择新图片', 'success');
    }

    showToast(message, type = 'success') {
        this.toast.textContent = message;
        this.toast.className = `toast ${type}`;
        this.toast.classList.add('show');
        
        setTimeout(() => {
            this.toast.classList.remove('show');
        }, 3000);
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    // 延迟检查以确保库文件完全加载
    setTimeout(() => {
        if (!window.Tesseract) {
            // 显示友好的错误信息
            const errorDiv = document.createElement('div');
            errorDiv.style.cssText = `
                position: fixed;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                background: #fff;
                padding: 30px;
                border-radius: 10px;
                box-shadow: 0 10px 30px rgba(0,0,0,0.3);
                text-align: center;
                z-index: 10000;
                max-width: 400px;
            `;
            errorDiv.innerHTML = `
                <h3 style="color: #e74c3c; margin-bottom: 15px;">⚠️ 加载失败</h3>
                <p style="margin-bottom: 20px; line-height: 1.6;">
                    OCR引擎加载失败，请检查网络连接或刷新页面重试。
                </p>
                <button onclick="location.reload()" style="
                    background: #3498db;
                    color: white;
                    border: none;
                    padding: 10px 20px;
                    border-radius: 5px;
                    cursor: pointer;
                ">刷新页面</button>
            `;
            document.body.appendChild(errorDiv);
            return;
        }

        // 初始化OCR扫描器
        const scanner = new OCRScanner();
    }, 500);
    
    // 全局错误处理
    window.addEventListener('error', (error) => {
        console.error('全局错误:', error);
        scanner.showToast('发生了意外错误，请刷新页面重试', 'error');
    });
    
    window.addEventListener('unhandledrejection', (event) => {
        console.error('未处理的Promise拒绝:', event.reason);
        scanner.showToast('网络请求失败，请检查网络连接', 'error');
        event.preventDefault();
    });
}); 